﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;

namespace App
{

    /// <summary>
    /// swagger 配置
    /// </summary>
    public static class SwaggerExtensin
    {

        /// <summary>
        /// 使用swagger
        /// 1. 中文注释
        /// 2. 版本控制
        /// 3. token请求
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="projectNames"></param>
        public static void UseAppSwaggerExtensin(this IServiceCollection builder, List<string> projectNames)
        {
            builder.AddSwaggerGen(options =>
            {
                foreach (var fileld in typeof(AppApiVersion).GetFields())
                {
                    options.SwaggerDoc(fileld.Name, new OpenApiInfo
                    {
                        Version = fileld.Name,
                        Title = "web API",
                        Description = $"web API,{fileld.Name}版本"
                    });
                }

                foreach (var item in projectNames)
                {
                    var apiFilename = $"{item}.xml";
                    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, apiFilename));
                }

                //添加安全注释
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "请输入token",
                    Name = "token",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = ""
                });
                //添加安全要求
                options.AddSecurityRequirement(new OpenApiSecurityRequirement {
                    {
                        new OpenApiSecurityScheme{
                            Reference =new OpenApiReference{
                                Type = ReferenceType.SecurityScheme,
                                Id ="Bearer"
                            }
                        },new string[]{ }
                    }
                });
            });
        }


        /// <summary>
        /// 使用swagger
        /// </summary>
        /// <param name="app"></param>
        public static void UseAppSwagger(this WebApplication app)
        {
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI(p =>
                {
                    foreach (var field in typeof(AppApiVersion).GetFields())
                    {
                        p.SwaggerEndpoint($"/swagger/{field.Name}/swagger.json", $"{field.Name}");
                    }
                });
            }
        }
    }
}
